package com.util;

import com.dao.BaseDao;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DataBaseUtil {
  /**
   * 静态加载块
   * 读取配置文件获取驱动
   */
  static{
    String driver = (String)ConfigManager.getProperties("driver");
    try {
      Class.forName(driver);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
  //声明静态驱动
  private static String driver;
  //声明静态url
  private static String url;
  //声明静态password
  private static String password;
  //声明静态user
  private static String user;

  /**
   * 读取配置文件获取
   */
  static{
    init();
  }
  public static void init(){
    //实例文件读取对象
    Properties properties =new Properties();
    //声明文件名 路径
    String file = "database.properties";
    //实例化文件读取对象 读取 file
    InputStream is = BaseDao.class.getClassLoader().getResourceAsStream(file);
    try {
      //加载 读取到的文件
      properties.load(is);
    } catch (IOException e) {
      e.printStackTrace();
    }
    //通过键获取到值
    driver = properties.getProperty("driver");
    url = properties.getProperty("url");
    user = properties.getProperty("userName");
    password = properties.getProperty("pwd");
  }

  /**
   * 读取配置拿链接
   */
  public static Connection getConnection(){
    Connection con = null;
    try {
      Class.forName(driver);
      con = DriverManager.getConnection(url,user,password);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    }
    return con;
  }

  /**
   * 连接池拿链接
   */
  public static Connection getCon(){
    //声明局部链接
    Connection con = null;
    try {
      Context context = new InitialContext();
      //拿数据
      DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/news");
      if(ds.getConnection()!=null){
        con =ds.getConnection();
      }else{
        throw new Exception("连接池获取异常！");
      }
    } catch (NamingException e) {
      e.printStackTrace();
    } catch (SQLException throwables) {
      throwables.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return con;
  }

  /**
   * 通用关闭方法
   * @param con
   * @param ps
   * @param rs
   */
  public static void closeAll(Connection con, PreparedStatement ps, ResultSet rs){
    if(con!=null){
      try {
        con.close();
      } catch (SQLException throwables) {
        throwables.printStackTrace();
      }
    }
    if(ps!=null){
      try {
        con.close();
      } catch (SQLException throwables) {
        throwables.printStackTrace();
      }
    }
    if(rs!=null){
      try {
        rs.close();
      } catch (SQLException throwables) {
        throwables.printStackTrace();
      }
    }
  }
}
